<template>
  <div class="orderDetail">
    <div class="header">
      <router-link to="/my-order" class="header-btnLeft">
        <img src="../assets/back-btn.png">
      </router-link>
      <h1 class="header-title">未支付订单详情</h1>
      <router-link v-if="orderData.displayedStatusStr == '已付款待使用'" to="/" class="header-btnRight"  ><img src="../assets/tabBar-home.png"></router-link>
    </div>
      <!--商品订单确认页-->
    <div class="order-wrap">
        <div class="order-wrap-title" v-if="orderData.orderType=='CustomMade'">
            <router-link :to="'/my-program-show/'+orderData.goodsId" class="order-wrap-title-jump" v-if="orderData.goodsId">{{orderData.orderName}}</router-link>
            <span v-else>{{orderData.orderName}}</span>
        </div>
        <div class="order-wrap-title" v-else>
            <router-link :to="'/show/'+orderData.goodsId" class="order-wrap-title-jump" v-if="orderData.goodsId">{{orderData.orderName}}</router-link>
            <span v-else>{{orderData.orderName}}</span>
        </div>
        <mt-cell class="order-wrap-nav" title="订单信息"></mt-cell>
        <mt-cell title="订单编号" :value="orderData.orderNo"></mt-cell>
        <mt-cell title="下单时间" :value="orderData.initAt"></mt-cell>
        <mt-cell title="订单状态" class="order-wrap-state" :value="orderData.displayedStatusStr"></mt-cell>

        <mt-cell class="order-wrap-nav" title="出行人及联系方式"></mt-cell>
        <mt-cell v-for="peo in orderData.orderPerson" :key="peo.person_name" :title="peo.person_name" :value="peo.person_num+'人'"></mt-cell>
        <mt-cell title="出行日期" :value="orderData.travelDate"></mt-cell>
        <!-- 多个出行人 -->
        <div v-if="orderData.bandiduser && orderData.bandiduser.length>0">
            <mt-cell v-for="(peo2,index) in orderData.bandiduser" :key="index" :title="index<1?'主出行人':'出行人'+(index+1)" :value="peo2.surname+peo2.firstname"></mt-cell>
        </div>
        <div v-else>
            <mt-cell title="出行人" :value="orderData.orderuser ? orderData.orderuser.surname+orderData.orderuser.firstname : ''"></mt-cell>
        </div>
        
        <mt-cell title="预定手机" :value="orderData.orderuser ? orderData.orderuser.Phone :''"></mt-cell>
        <mt-cell title="预定邮箱" :value="orderData.orderuser ? orderData.orderuser.email :''"></mt-cell>
        <mt-cell class="order-wrap-longtext" title="接待地址" :value="orderData.serveAddress"></mt-cell>
        <mt-cell class="order-wrap-paidtime" v-if="countDownTime.min!='00' || countDownTime.sec!='00'" title="支付时间" :value="countDownTime.min+'分'+countDownTime.sec+'秒'"></mt-cell>
        <div class="order-wrap-cancelbtn" v-if="orderData.displayedStatusStr == '待付款' || orderData.displayedStatusStr == '已过期'">
            <span>（如需重新下单请删除该订单） </span>
            <mt-button @click.native="cancelOrder" size="small" plain>删除订单</mt-button>
        </div>
    </div>
      <!--拼游订单确认页-->

    <div class="h120"></div>
    <div class="buyBar" v-if="countDownTime.min!='00' || countDownTime.sec!='00'">
        <div class="buyBar-item">
            <div class="buyBar-item-title">总价</div>
            <div class="buyBar-item-price">¥ {{orderData.foldMoney}}</div>
        </div>
        <div class="buyBar-buy" @click='choosePayType'>立即支付</div>
    </div>
    <mt-actionsheet
    :actions="payActions"
    v-model="payState">
    </mt-actionsheet>
  </div>
</template>

<script>
import { Toast, MessageBox, Indicator } from "mint-ui";
import wxShare from "../store/wxShare";

export default {
  name: "My-Order-Deatail-Unpaid",
  data() {
    return {
        order_no:"",
        orderData: {},
        countDownTime:"",
        payActions:[],
        payState:false,
        stripePayInfo:{}
    };
  },
  methods: {
    getOrderData() {
      let _that = this;
      var params = {
          order_no: this.order_no
      };
      _that.axios
        .post("/repeatorderdetail", params,true)
        .then(res => {
            if(res.data.msg){
                return;
            }
            _that.orderData = res.data;
            _that.countDown();
            _that.share(res.data);
        })
        .catch(err => console.log(err));
    },
    timeFormat(param) {//小于10的格式化函数
        return param < 10 ? '0' + param : param;
    },
    countDown(){
        if(this.orderData.displayedStatusStr == '已付款待使用'){
            this.countDownTime = {
                min: '00',
                sec: '00'
            }
            return;
        };
        let createTime = this.orderData.initAt.split("北京时间")[1].replace(/-/g,'/');
        let newTime = new Date().getTime();
        let endTime = new Date(createTime).getTime() + (1800 * 1000); //结束时间+30分钟
        let _time = null;
        // 如果活动未结束，对时间进行处理
        if (endTime - newTime > 0) {
            let time = (endTime - newTime) / 1000;
            // 获取天、时、分、秒
            //let day = parseInt(time / (60 * 60 * 24));
            //let hou = parseInt(time % (60 * 60 * 24) / 3600);
            let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
            let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
            _time = {
                //day: this.timeFormat(day),
                //hou: this.timeFormat(hou),
                min: this.timeFormat(min),
                sec: this.timeFormat(sec)
            }
        } else {//活动已结束，全部设置为'00'
            _time = {
                // day: '00',
                // hou: '00',
                min: '00',
                sec: '00'
            }
        }
        this.countDownTime = _time;
        let timer = setTimeout(this.countDown, 1000);
        if(_time.min == '00' && _time.sec == '00'){
            clearInterval(timer);
            this.orderData.displayedStatusStr = "已过期";
        }
    },
    choosePayType() {
        this.payState = true;
        this.stripePayInfo.moneyArr = this.orderData.moneyArr;
        this.stripePayInfo.orderData = {
            goods_id:this.orderData.goodsId,
            order_id:this.orderData.orderId,
            orderType:this.orderData.orderType,
            order_no:this.orderData.orderNo,
        }
    },
    // 开始支付
    beginPay(){
        let fromApp = 0;
        if(this.$store.state.appNestState) {
            fromApp = 1;
        }
        let postData = {
            order_id:this.orderData.orderId,
            orderType:this.orderData.orderType,
            order_no:this.orderData.orderNo,
        };

        let appid = window.localStorage.appid;
        if(fromApp && appid && appid.length > 0) {
            postData.appid = appid;
        }
        this.axios.post('/wxpay', postData).then(res => {
            if(!fromApp) {
                var params = {
                    appId: res.data.appId,
                    timeStamp: res.data.timeStamp,
                    nonceStr: res.data.nonceStr,
                    package: res.data.package,
                    paySign: res.data.paySign
                };
                this.wxPay(params);
            } else {
                this.appWXPay(res.data);
            }
        }).catch(err => console.log(err));
    },
    // 微信支付
    wxPay(params){
        var _that=this
        function onBridgeReady(){
            console.log('onBridgeReady');
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                    "appId":params.appId,     //公众号名称，由商户传入
                    "timeStamp":params.timeStamp,  //时间戳，自1970年以来的秒数
                    "nonceStr":params.nonceStr, //随机串
                    "package":params.package,
                    "signType":"MD5",         //微信签名方式
                    "paySign":params.paySign //微信签名
                },
                function(res){
                    if(res.err_msg == "get_brand_wcpay_request:ok" ){
                        _that.$router.push({path:'/pay-success',query:{goods_id:_that.goods_id,order_id: _that.order_id}});
                    }
                });
        }
        if (typeof WeixinJSBridge == "undefined"){
            if( document.addEventListener ){
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            }else if (document.attachEvent){
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
        }else{
            onBridgeReady();
        }
    },
    appWXPay(params) {
        let that = this;
        let data = {
        command: 'wechatPay',
        content: {
            action:'wechatPay',
            orderId: that.orderData.orderId,
            goodsId: that.orderData.goodsId,
            partnerId: params.partnerid,
            prepayId: params.prepayid,
            timeStamp: params.timestamp,
            package: params.package,
            nonceStr: params.noncestr,
            sign: params.sign
        }
        };
        window.postMessage(JSON.stringify(data))
    },
    // 删除订单
    cancelOrder() {
        var _that = this;
        MessageBox({
            title: '提示',
            message: '是否删除当前订单？',
            confirmButtonText:'删除',
            showCancelButton: true
        }).then(res=>{
            if(res=='confirm'){
                _that.axios.post('wap/member/delorder', {
                        order_id:_that.orderData.orderId,
                        orderType:_that.orderData.orderType,
                        order_no:_that.orderData.orderNo,
                    },true
                ).then(res => {
                    Toast({message: res.msg, duration: 1500});
                    if(_that.orderData.orderType=='CustomMade'){
                        _that.$router.replace('/my')
                    }else {
                        _that.$router.replace('/show/'+_that.orderData.goodsId)
                    }
                }).catch(err => console.log(err));
            }
        });
    },
    share(order) {
        let _orderName = (order.orderSubType && order.orderType == 'Vehicle') ? order.name : order.orderName;
        wxShare({ title: "我的订单",desc: _orderName, debug: false }, function() {
            console.log("分享成功");
        });
    }
  },
  created(){
        if(!sessionStorage.reloaded){
            sessionStorage.reloaded = true;
            location.reload();
        }
    },
  mounted() {
    window.scrollTo(0,0);
    this.order_no = this.$route.query.order_no;
    this.getOrderData();
    let _that = this;
    this.payActions = [
        {
            name:"微信支付",
            method:function(){
                _that.beginPay();
            }
        },
        {
            name:"信用卡支付",
            method:function(){
                _that.$router.push({path:'/stripe-pay',query: { order_id: _that.order_id,goods_id: _that.goods_id,orderType:_that.orderType,order_no:_that.order_no,totalPricePay:_that.totalPricePay}})
            }
        }
    ];
  },
  beforeRouteLeave(to, from, next) {
    if (to.name == "stripe-pay") {
        sessionStorage.stripePayInfo = JSON.stringify(this.stripePayInfo);
        next();
    }else if(this.orderData.displayedStatusStr == '已付款待使用' || to.name == "pay-success"){
        next();
    }else{
        if(to.name == 'show'){
            next();
            return;
        }
        MessageBox({
            title: "提示",
            message: "是否删除当前未支付订单？红包优惠券将返回您的账户中。",
            showCancelButton: true,
            confirmButtonText: "是",
            cancelButtonText: "否",
        }).then(res => {
            if(res=='confirm'){
                this.axios.post('wap/member/delorder', {
                        order_id:this.orderData.orderId,
                        orderType:this.orderData.orderType,
                        order_no:this.orderData.orderNo,
                    },true
                ).then(res => {
                    Toast({message: res.msg, duration: 1500});
                    if(this.orderData.orderType=='CarPool'){
                        this.$router.replace('/my')
                    }else{
                        this.$router.replace('/show/'+this.orderData.goodsId)
                    }
                }).catch(err => console.log(err));
            }else{
                this.$router.replace('/show/'+this.orderData.goodsId)
            }
        });
    }
  }
};
</script>

<style lang="scss">
@import "../assets/base";

.orderDetail .h30 {
  height: rpx(30);
  background: $bgcolor1;
}

.orderDetail .h120 {
  height: rpx(200);
  background: $bgcolor1;
}

.orderDetail  {
  background: $bgcolor1;
  min-height: 100%;
}

.orderDetail .header {
  display: flex;
  align-items: center;
  padding: rpx(30);
  justify-content: space-between;
  background: $color0;
  &-btnLeft {
    width: rpx(64);
    height: rpx(64);
    padding-top: rpx(16);
    img {
      width: rpx(32);
      height: rpx(32);
    }
  }
  &-btnRight{
    width: rpx(64);
    height: rpx(64);
    padding-top: rpx(16);
    img{
        width: rpx(42);
        height: rpx(42);
    }
  }
  &-title {
    flex: 1;
    font-size: rpx(36);
    text-align: center;
    font-weight: normal;
  }
}
.orderDetail .mint-cell{
    min-height: rpx(90);
}
.orderDetail .mint-cell-title{
    min-width: rpx(100);
}
.orderDetail .order-wrap{
    background: #ffffff;
    margin-top: rpx(30);
    padding: rpx(20) rpx(20) rpx(100) rpx(20);
    &-title {
        font-size: rpx(34);
        font-weight: 400;
        padding: rpx(20) 0;
        color: #FB7D33;
        line-height: 1.4;
        &-jump {
            color: #FB7D33;
            text-decoration: underline;
        }
    }
    
    &-nav {
        font-size: rpx(30);
        font-weight: 400;
        font-weight: 600;
        display: flex;
        align-items: center;
        min-height: rpx(120);
    }
    
    &-nav:before {
        content: "";
        display: inline-block;
        width: rpx(10);
        height: rpx(28);
        background: #FB7D33;
    }
    &-money .mint-cell-value{
       color: red;
    }
    &-state .mint-cell-value{
       color: #FB7D33;
    }
    &-longtext .mint-cell-value{
       padding: rpx(20px) 0 rpx(20px) rpx(20px);
       text-align: right;
    }
    &-paidtime .mint-cell-value,&-paidtime .mint-cell-text{
       color: #FB7D33;
    }
    &-cancelbtn{
        span{
            font-size: rpx(26);
            color: #888;
        }
        text-align: right;
        margin: rpx(15);
    }
    
}
.orderDetail .mint-cell .mint-cell-wrapper{
    font-size: rpx(28);
}
.orderDetail .buyBar {
    position: fixed;
    z-index: 9998;
    left: 0;
    right: 0;
    bottom: 0;
    border-top: $color2 solid 1px;
    background: $color0;
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    &-item {
        flex: 1;
        height: rpx(90);
        &-title {
            padding: rpx(10) 0 0 rpx(30);
            font-size: rpx(24);
        }
        &-price {
            padding-top: rpx(10);
            padding-left: rpx(30);
            font-size: rpx(40);
            color: $color3;
        }
    }
    &-item:last-child {
        border-right: none;
    }
    &-buy {
        width: rpx(300);
        height: rpx(90);
        line-height: rpx(90);
        background: linear-gradient(to left, #ff5722, #ffc000);
        text-align: center;
        font-size: rpx(40);
        color: $color0;
    }
    &-active {
        color: $color3;
    }

}
</style>